﻿/// <reference path="new_XrmPage_vsdoc.js" />
/// <reference path="new_jquery.js" />
/// <reference path="new_json.js" />
/// <reference path="new_XrmServiceToolkit.js" />

var common = {
    getAttrValue: function (attrId) {
        var attr = Xrm.Page.getAttribute(attrId);
        if (attr) {
            var type = attr.getAttributeType();
            var value = attr.getValue();
            switch (type) {
                case "boolean":
                case "decimal":
                case "double":
                case "integer":
                case "money":
                case "memo":
                case "string":
                    return value;
                    break;
                case "optionset":
                    return attr.getText();
                    break;
                case "datetime":
                    return (value != null) ? value.toString() : null;
                    break;
                case "lookup":
                    var data;
                    if (value != null) {
                        for (var i in value) {
                            data = value[i].name;
                        }
                    }
                    else
                        data = value;

                    return data;
                    break;
                default:
                    return null;
            }

            return attr.getValue();
        }
        else {
            common.showMessage("getAttrValue: Невозможно найти аттрибут с id = " + attrId);
            return null;
        }
    },
    getAttrKey: function (attrId) {
        var attr = Xrm.Page.getAttribute(attrId);
        if (attr) {
            var type = attr.getAttributeType();
            var value = attr.getValue();
            switch (type) {
                case "boolean":
                case "decimal":
                case "double":
                case "integer":
                case "money":
                case "memo":
                case "optionset":
                case "string":
                    return value;
                    break;
                case "datetime":
                    return (value != null) ? value : null;
                    break;
                case "lookup":
                    var data;
                    if (value != null) {
                        for (var i in value) {
                            data = value[i].id;
                        }
                    }
                    else
                        data = value;

                    return data;
                    break;
                default:
                    return null;
            }

            return attr.getValue();
        }
        else {
            common.showMessage("getAttrValue: Невозможно найти аттрибут с id = " + attrId);
            return null;
        }
    },
    showControl: function (controlId, required) {
        var control = Xrm.Page.ui.controls.get(controlId);
        if (control) {
            control.setVisible(true);
            //Control
            if (document.getElementById(controlId + "_d") != null)
                document.getElementById(controlId + "_d").style.display = "";
            //Label
            if (document.getElementById(controlId + "_c") != null)
                document.getElementById(controlId + "_c").style.display = "";
            if (required == true)
                common.setRequiredControl(controlId);
        }
    },
    hideControl: function (controlId, leaveValue) {
        var control = Xrm.Page.ui.controls.get(controlId);
        if (control) {
            control.setVisible(false);
            //Control
            if (document.getElementById(controlId + "_d") != null)
                document.getElementById(controlId + "_d").style.display = "none";
            //Label
            if (document.getElementById(controlId + "_c") != null)
                document.getElementById(controlId + "_c").style.display = "none";
            if (!leaveValue)
                common.setAttrValue(controlId, null);
            common.unsetRequiredControl(controlId);
        }
    },
    setAttrValue: function (attrId, attrValue, noFireOnChange) {
        var attr = Xrm.Page.getAttribute(attrId);
        if (attr) {
            var oldValue = attr.getValue();
            if (!common.isEqualValues(attr, oldValue, attrValue)) {
                attr.setValue(attrValue);
                if (attr.getSubmitMode() != "dirty")
                    attr.setSubmitMode("dirty");
                if (common.isNull(noFireOnChange, false) != true)
                    attr.fireOnChange();
            }

            if (attr.getIsDirty() == true)
                attr.setSubmitMode("always");
            else
                attr.setSubmitMode("dirty");
        }
        else if (!attr)
            common.showMessage("setAttrValue: Невозможно найти аттрибут с id = " + attrId);
    },
    isEqualValues: function (attr, value1, value2) {
        var type = attr.getAttributeType();
        switch (type) {
            case "lookup":
                var id1 = (value1 && value1[0] && value1[0].id) ? value1[0].id.toLowerCase() : null;
                var id2 = (value2 && value2[0] && value2[0].id) ? value2[0].id.toLowerCase() : null;
                return (id1 == id2);
                break;
            default:
                return (value1 == value2);
        }
    },
    isNull: function (value, valueIfNull) {
        if (value == null)
            return valueIfNull;
        else
            return value;
    },
    showMessage: function (message) {
        alert(message);
    },
    setRequiredControl: function (controlId, isRequired) {
        Xrm.Page.getAttribute(controlId).setRequiredLevel((isRequired == null || isRequired == true) ? "required" : "none");
        if (isRequired == null || isRequired == true)
            common.showControl(controlId);
    },
    unsetRequiredControl: function (controlId) {
        Xrm.Page.getAttribute(controlId).setRequiredLevel("none");
    },
    setDisabledControl: function (controlId, disabled) {
        Xrm.Page.ui.controls.get(controlId).setDisabled(disabled);
        Xrm.Page.getAttribute(controlId).setSubmitMode("dirty");
    },
    showAllTabIds: function () {
        var tabs = Xrm.Page.ui.tabs.get();
        var mess = "Все табы:\n";
        for (i = 0; i < tabs.length; i++) {
            mess += tabs[i].getName() + " : " + tabs[i].getLabel() + "\n";
        }
        console.log(mess);
    },
    showAllSectionIds: function () {
        var tabs = Xrm.Page.ui.tabs.get();
        var mess = "Все табы и вложенные секции:\n";
        for (i = 0; i < tabs.length; i++) {
            mess += "Таб " + tabs[i].getName() + " | " + tabs[i].getLabel() + ":\n";
            sections = tabs[i].sections.get();
            for (j = 0; j < sections.length; j++)
                mess += " - " + sections[j].getName() + " | " + sections[j].getLabel() + "\n";
        }
        console.log(mess);
    },
    showAllNavItems: function () {
        var navItems = Xrm.Page.ui.navigation.items.get();
        var mess = "Меню навигации:\n";
        for (i in navItems) {
            var nav = navItems[i];
            mess += nav.getId() + " | " + nav.getLabel() + "\n";
        }
        console.log(mess);
    },
    getIsDirtyAttributes: function () {
        var mess = "Измененные поля:\n";
        Xrm.Page.data.entity.attributes.forEach(function (attr, i) {
            if (attr.getIsDirty())
                mess += attr.getName() + "\n";
        });
        console.log(mess);
    },
    getIsDirtyAttributes2: function () {
        var mess = "Измененные поля:\n";

        var entity = null;
        var controls = null;

        try {
            entity = parent.Xrm.Page.data.entity;
            controls = parent.Xrm.Page.ui.controls;
        }
        catch (e) {
            entity = Xrm.Page.data.entity;
            controls = Xrm.Page.ui.controls;
        }

        entity.attributes.forEach(function (attr, i) {
            if (attr.getIsDirty()) {

                mess += controls.get(attr.getName()).getLabel() + "\n";

                //            mess += attr.getName() + "\n";
            }
        });
        return (mess);
    },
    getQuerystringParameterByName: function (name, address) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(address);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    },
    showTab: function (tabId) {
        Xrm.Page.ui.tabs.get(tabId).setVisible(true);
    },
    hideTab: function (tabId, clearAttributes, excludedAttributes) {
        var tab = Xrm.Page.ui.tabs.get(tabId);
        if (tab) {
            if (tab[0])
                tab = tab[0];
            tab.setVisible(false);
            if (clearAttributes) {
                tab.sections.forEach(function (section, sIndex) {
                    section.controls.forEach(function (control, cIndex) {
                        if (control.getAttribute) {
                            var attr = control.getAttribute();
                            if (attr && !(excludedAttributes && attr.getName().toLowerCase() in excludedAttributes))
                                attr.setValue();
                        }
                    });
                });
            }
        }
        else
            common.showMessage("Невозможно найти раздел " + tabId);
    },
    getSection: function (id) {
        var sectionFound;
        Xrm.Page.ui.tabs.forEach(function (tab, i) {
            tab.sections.forEach(function (section, j) {
                if (section.getName() == id)
                    sectionFound = section;

            });
        });
        if (!sectionFound)
            common.showMessage("Невозможно найти секцию " + id);
        return sectionFound;
    },
    showSection: function (sectionId) {
        var section = common.getSection(sectionId);
        if (section)
            section.setVisible(true);
    },
    hideSection: function (sectionId, clearAttributes, excludedAttributes) {
        var section = common.getSection(sectionId);
        if (section) {
            section.setVisible(false);
            if (clearAttributes) {
                section.controls.forEach(function (control, cIndex) {
                    if (control.getAttribute) {
                        var attr = control.getAttribute();
                        if (attr && !(excludedAttributes && attr.getName().toLowerCase() in excludedAttributes))
                            attr.setValue();
                    }
                });
            }
        }
    },
    showNavItem: function (navItemId) {
        var navItem = Xrm.Page.ui.navigation.items.get(navItemId);
        if (navItem)
            if (!navItem.getVisible())
                navItem.setVisible(true);
    },
    hideNavItem: function (navItemId) {
        var navItem = Xrm.Page.ui.navigation.items.get(navItemId);
        if (navItem)
            if (navItem.getVisible())
                navItem.setVisible(false);
    },
    showSubgrid: function (subgridId, count) {
        count = (count) ? count : 1;
        var subgrid = Xrm.Page.getControl(subgridId);
        if (subgrid && subgrid._control && subgrid._control.get_innerControl() && subgrid._control._element && subgrid._control._element.readyState == "complete") {
            subgrid.setVisible(true);
        }
        else if (count < 5) {
            count++;
            setTimeout(function () { showSubgrid(subgridId, count) }, 500);
        }
    },
    hideSubgrid: function (subgridId, count) {
        count = (count) ? count : 1;
        var subgrid = Xrm.Page.getControl(subgridId);
        if (subgrid && subgrid._control && subgrid._control.get_innerControl() && subgrid._control._element && subgrid._control._element.readyState == "complete") {
            subgrid.setVisible(false);
        }
        else if (count < 5) {
            count++;
            setTimeout(function () { hideSubgrid(subgridId, count) }, 500);
        }
    },
    getPreLoader: function () {
        var preLoader;
        if ($("#ajaxPreLoader").length == 0) {
            var windowWidth = $(document).width();
            var windowHeight = $(document).height();

            preLoader = $("<div>");
            preLoader.attr("id", "ajaxPreLoader");
            preLoader.css({ "display": "none",
                "width": "300",
                "height": "300",
                "position": "absolute",
                "left": ((windowWidth / 2) - 150) + "px",
                "top": ((windowHeight / 2) - 150) + "px"
            });

            var img = $("<img>");
            img.css({ "width": "300", "height": "300" });
            img.attr("src", "/WebResources/new_gif");
            $(img).appendTo(preLoader);

            $(preLoader).appendTo($("body"));

        }
        else {
            preLoader = $("#ajaxPreLoader");
        }
        return preLoader;
    },
    showPreLoader: function () {
        var q = common.getPreLoader();
        q.show();
    },
    hidePreLoader: function () {
        var q = common.getPreLoader();
        q.hide();
    },
    hideMegaWindow: function () {
        var appendto = $(document.parentWindow.parent.document.body);
        if ($("#mega_window", appendto).length > 0) {
            $("#mega_window", appendto).remove();
        }
    },
    showMegaWindow: function () {
        var appendto = $(document.parentWindow.parent.document.body);
        wnd = "<div id='mega_window' style='background-color:#fff;z-index:999;clear:both;position:absolute;height:" + ($(appendto).height() - 5) + "px;width:" + $(appendto).width() + "px'>" +
        "<table style='height:100%;width:100%;background-color:#eff3f7'>" +
        "<tr>" +
	        "<td style='vertical-align: middle' align='center'>" +
		        "<IMG id='loading' alt='' src='/_imgs/AdvFind/progress.gif'/>" +
	        "</td>" +
        "</tr>" +
        "</table>" +
        "</div>";
        $(wnd).appendTo(appendto);
        $(window).resize(function () {
            if ($("#mega_window").length > 0)
                $('#mega_window').css({ "width": ($(appendto).width() - 5) + "px", "height": ($(appendto).height() - 5) + "px" });
        });
    }
}
